<template>
  <div class="pageBox pl20 pr20 pt10">
    <div class="tabBox">
      <div class="flexBox">
        <span v-for="item in statusList" :key="item.value"
          :class="['block', 'fs24', 'c-fff', 'tabItem', { activeTab: curStatus === item.value }]"
          @click="changeStatus(item.value)">{{ item.name }}</span>
      </div>
    </div>

    <div v-if="isShowSkeleton" class="mt20">
      <van-skeleton title :row="5" />
    </div>
    <div v-else class="orderScrollWrap mt20" ref="orderScrollWrap">
      <van-empty description="暂无数据" v-if="!total" />

      <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="">
        <van-list v-if="total > 0" v-model:loading="loading" :finished="finished" finished-text="没有更多了"
          v-model:error="error" error-text="请求失败，点击重新加载" @load="onLoad">
          <div v-for="item in list" :key="item.id" class="orderList">
            <div class="bg-ff mb20 pl20 pr20 pt20 pb20 orderItem">
              <div class="flexBox flexBetween header">
                <span class="pick block fs24 c-fff">{{ eatType[item.dining_method] }}</span>
                <span class="block fs24">{{ orderStatus[item.status] || '-' }}</span>
              </div>
              <div class="line mt15 mb15"></div>
              <div class="foodItem pb30">
                <div v-for="food in item.items" :key="food.id" class="mb20">
                  <div class="flexBox aiCenter">
                    <img :src="handleImgSrc(food.menu_photo)" alt="" class="food-img">
                    <div class="flexItem ml15">
                      <div class="flexBox flexBetween">
                        <span class="fs26 block">{{ food.menu_name }}</span>
                        <div class="fs24 c-666">x {{ food.quantity }}</div>
                      </div>
                      <span class="fs24 c-666">{{ food.menu_fee }}</span>
                    </div>
                  </div>
                </div>
                <div v-if="item.remark" class="fs24 c-666 oneLine">备注：{{ item.remark }}</div>
              </div>
              <div class="flexBox flexBetween mt15">
                <span class="block fs24 c-666">{{ changeTime(item.create_time, 'YYYY-MM-DD HH:mm') }}</span>
                <div class="fs24">共{{ item.items.length }}件商品 合计：<span class="f600">¥{{ item.total_fee }}</span></div>
              </div>
              <div class="flexBox aiCenter flexBetween footerBtns mt15">
                <!-- <img :src="deleteIcon" alt="" width="20px" height="22px" @click="handleDel(item.id)"> -->
                <van-popover placement="top-start" theme="dark">
                  <div class="pl30 pr30 pt10 pb10">
                    <span v-if="item.status === 1" class="block fs24 pt10 pb10 menuBottomBorder"
                      @click="handleRefund(item.id)">申请退款</span>
                    <span class="block fs24 pt10 pb10" @click="handleDel(item.id)">删除订单</span>
                  </div>
                  <template #reference>
                    <div class="fs24 c-333">更多</div>
                  </template>
                </van-popover>
                <div class="flexBox flexBetween">
                  <span v-if="item.status === 0" class="block fs22 payBtn" @click="handlePay(item)">立即支付</span>
                  <span v-if="item.status === 1" class="block fs22 btn ml15"
                    @click="handleComplete(item.id)">用餐完成</span>
                  <span v-if="item.status === 2" class="block fs22 btn mr15" @click="handleAgain(item)">再来一单</span>
                  <span v-if="item.status === 2 && !item.reviewed" class="block fs22 btn" @click="handleScore(item)">
                    评价
                  </span>
                  <span v-if="item.status === 2 && item.reviewed" class="block fs22 btn" @click="handleScore(item)">查看评价
                  </span>
                  <span v-if="item.remark || item.refundInfo.userRemark || item.refundInfo.merchantRemark"
                    class="block fs22 btn ml15" @click="handleRemarkDetail(item)">备注详情</span>
                </div>
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <van-popup v-model:show="refundPopup.show" position="bottom" :style="{ height: '35%' }" closeable
      :close-on-click-overlay="false" @click-close-icon="refundPopup.show = false" @closed="onRefundPopupClosed"
      style="background: #F7F8FA;">
      <div class="mt100 pl30 pr30">
        <van-cell-group>
          <van-field v-model="refundPopup.remark" rows="2" autosize label="备注" type="textarea" maxlength="100"
            placeholder="请输入备注" show-word-limit />
        </van-cell-group>
        <div class="mt30">
          <van-button type="primary" block @click="handleRefundSubmit">确定</van-button>
        </div>
      </div>
    </van-popup>

    <van-popup v-model:show="remarkPopup.show" position="bottom" :style="{ height: '35%' }" closeable
      :close-on-click-overlay="false" @click-close-icon="remarkPopup.show = false" @closed="onRemarkPopupClosed">
      <div class="mt100 pl30 pr30">
        <div class="fs30">用户备注</div>
        <span class="block fs26 c-666 mt15">备注：{{ remarkPopup.data.remark || '-' }}</span>
        <span class="block fs26 c-666 mt5">申请退款备注：{{ remarkPopup.data.refundInfo?.userRemark || '-' }}</span>
        <div class="fs30 mt50">商家备注</div>
        <span class="block fs26 c-666 mt15">申请退款备注：{{ remarkPopup.data.refundInfo?.merchantRemark || '-' }}</span>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { orderComplete, orderDelete, orderList, orderRefundApply } from '@/api/order'
import { eatType, orderStatus } from '@/types/mock'
import { orderListType } from '@/types/orderTypes'
import { changeTime, handleImgSrc } from '@/utils'
// import deleteIcon from '@/assets/images/delete.png'
import { showConfirmDialog, showToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import orderStore from '@/store/modules/order'
import menuStore from '@/store/modules/menu'

// defineOptions({
//   name: 'orderList'
// })
const order = orderStore()
const menu = menuStore()

const list = ref<orderListType[]>([])
const total = ref(0)
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(true)
const error = ref(false)
const isShowSkeleton = ref(true)

const refundPopup = reactive({
  show: false,
  id: 0,
  remark: ''
})
const curStatus = ref(Number(sessionStorage.getItem('curOrderStatus')) || -1)
const orderScrollWrap = ref<HTMLDivElement | null>(null)
const pageData = reactive({
  page: 1,
  pageSize: 10
})
const remarkPopup = reactive({
  show: false,
  data: {}
})

const router = useRouter()
const route = useRoute()

const statusList = computed(() => {
  const allOrder = {
    name: '全部',
    value: -1
  }
  const statusList = Object.keys(orderStatus).filter(key => isNaN(Number(key))).map(key => ({
    name: key,
    value: orderStatus[key]

  }))
  return [allOrder, ...statusList]
})

const changeStatus = (status: string) => {
  curStatus.value = status
  resetList()
  getList()
}

const getList = async () => {
  if (list.value.length >= total.value && list.value.length > 0) {
    loading.value = false
    finished.value = true
    return
  }
  try {
    const params = {
      ...pageData,
      status: +curStatus.value
    }
    if (curStatus.value === -1) {
      delete params.status
    }
    const { data } = await orderList(params)
    if (data.code === 0) {
      isShowSkeleton.value = false
      list.value = [...list.value, ...data.data.entries]
      total.value = data.data.total
      finished.value = list.value.length === total.value
    }
  } catch (err) {
    error.value = true
  }
  loading.value = false
}

const onLoad = () => {
  setTimeout(() => {
    pageData.page++
    getList()
  }, 500)
}

const onRefresh = () => {
  resetList()
  setTimeout(() => {
    getList()
    refreshing.value = false
  }, 500)
}

const handleDel = (id: number) => {
  showConfirmDialog({
    title: '删除',
    message: '确定要删除该订单吗？',
    confirmButtonColor: '#40a9ff'
  }).then(async () => {
    const { data } = await orderDelete({ id })
    if (data.code === 0) {
      showToast('已删除')
      resetList()
      getList()
    }
  }).catch(() => {
    return
  })
}

const handleComplete = async (id: number) => {
  showConfirmDialog({
    title: '用餐确认',
    message: '亲爱的顾客，感谢您的用餐！若您确认已用餐完毕，请点击"确认"按钮，期待您再次光临',
    confirmButtonColor: '#40a9ff',
    messageAlign: 'left'
  }).then(async () => {
    const { data } = await orderComplete({ id })
    if (data.code === 0) {
      showToast('已完成')
      resetList()
      getList()
    }
  }).catch(() => {
    return
  })
}

const handleRefundSubmit = async () => {
  if (!refundPopup.remark) return showToast('请输入退款备注')
  const { data } = await orderRefundApply({
    order_id: refundPopup.id,
    user_remark: refundPopup.remark
  })
  if (data.code === 0) {
    showToast('已申请退款')
    refundPopup.show = false
    resetList()
    getList()
  } else {
    showToast(data.msg)
  }
}

const handleRefund = (id: number) => {
  refundPopup.show = true
  refundPopup.id = id
}

const handleScore = (item: orderListType) => {
  sessionStorage.setItem('curOrderStatus', curStatus.value.toString())
  router.push({
    name: 'orderScore',
    query: {
      id: item.id,
      ...(item.reviewed ? { reviewed: +item.reviewed } : {})
    }
  })
}

const handlePay = (data: orderListType) => {
  const newItem = data.items.map(item => ({
    id: item.menu_id,
    fee: item.menu_fee,
    name: item.menu_name,
    quantity: item.quantity,
    photo_url: item.menu_photo
  }))
  order.setCart(newItem)
  order.setConfig({
    dining_method: data.dining_method,
    remark: data.remark,
    order_id: data.id
  })
  router.push('confirmOrder')
}

const handleAgain = (data: orderListType) => {
  const newItem = data.items.map(item => ({
    id: item.menu_id,
    fee: item.menu_fee,
    name: item.menu_name,
    quantity: item.quantity,
    photo_url: item.menu_photo
  }))
  menu.setMenu(newItem)
  router.push('menu')
}

const resetList = () => {
  list.value = []
  pageData.page = 1
}

const handleRemarkDetail = (item: orderListType) => {
  remarkPopup.show = true
  remarkPopup.data = item
}

const onRefundPopupClosed = () => {
  refundPopup.id = 0
  refundPopup.remark = ''
}

const onRemarkPopupClosed = () => {
  remarkPopup.data = {}
}

// 滚动时显示滚动条
const handleScroll = () => {
  if (orderScrollWrap.value) {
    // 现代浏览器：修改滚动条颜色
    orderScrollWrap.value.style.scrollbarColor = 'rgba(191, 191, 191, 0.8) rgba(191, 191, 191, 0.2)'

    // 清除自动隐藏的定时器
    if (window.scrollbarTimer) {
      clearTimeout(window.scrollbarTimer)
    }

    // 滚动停止后，延迟隐藏滚动条
    window.scrollbarTimer = setTimeout(() => {
      orderScrollWrap.value!.style.scrollbarColor = 'rgba(0, 0, 0, 0) rgba(0, 0, 0, 0.1)'
    }, 500)
  }
}

onMounted(() => {
  getList()
  if (orderScrollWrap.value) {
    orderScrollWrap.value.addEventListener('scroll', handleScroll)
  }
})

onUnmounted(() => {
  const curStatus = route.name as string
  if (!['orderScore'].includes(curStatus)) {
    sessionStorage.removeItem('curOrderStatus')
  }
  if (orderScrollWrap.value) {
    orderScrollWrap.value.removeEventListener('scroll', handleScroll)
    clearTimeout(window.scrollbarTimer)
  }
})
</script>

<style lang="scss" scoped>
.pageBox {
  background: #F7F7F7;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .tabBox {
    background: #40a9ff;
    height: 60px;
    line-height: 60px;
    border-radius: 50px;
    position: sticky;
    top: 0;
    z-index: 10;

    .tabItem {
      text-align: center;
      display: block;
      width: 25%;
    }
  }

  .orderScrollWrap {
    flex: 1;
    overflow-y: auto;
    scrollbar-width: thin;
    // 现代浏览器：设置滚动条为薄型
    scrollbar-color: rgba(0, 0, 0, 0) rgba(0, 0, 0, 0.1);
    // 初始透明，滚动时变色
    transition: scrollbar-color 0.3s ease;

    // WebKit 内核浏览器（Chrome、Safari 等）
    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.1);
      // 轨道浅灰色
    }

    &::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0);
      // 初始透明
      border-radius: 2px;
      transition: background-color 0.3s ease;
    }

    &:hover::-webkit-scrollbar-thumb,
    &:scrollbarthumbvertical::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0.4);
    }
  }

  .orderList {
    margin-bottom: 15px;

    &:last-child {
      margin-bottom: 0;
    }

    .orderItem {
      border-radius: 15px;

      &:last-child {
        margin-bottom: 0;
      }

      .food-img {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        object-fit: cover;
      }
    }

    .header {
      .pick {
        border-radius: 5px;
        padding: 0 10px;
        background: #C2A379;
      }
    }

    .line {
      width: 100%;
      height: 1px;
      background: #000000;
      opacity: 0.08;
    }

    .foodItem {
      border-bottom: 1px dashed #edebeb;
    }
  }

  .footerBtns {
    .btn {
      padding: 5px 20px;
      border-radius: 35px;
      border: 1px solid #40a9ff;
      color: #40a9ff;
    }

    .payBtn {
      padding: 8px 30px;
      border-radius: 35px;
      background: #FF3419;
      color: #fff;
    }
  }
}

.menuBottomBorder {
  border-bottom: 1px solid #999999;
}

.van-cell__value {
  text-align: left !important;
}

.van-button {
  padding: 0 30px;
}

.activeTab {
  background: #fff;
  color: #40a9ff;
  border-radius: 50px;
}
</style>